<template>
  <div class="app-container">
    <!-- 筛选区域 -->
    <el-card class="card-header">
      <el-form :model="filterForm">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="采样日期">
              <el-date-picker v-model="filterForm.dateRange" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采样点位">
              <el-select v-model="filterForm.samplingLocation" placeholder="请选择采样点位" clearable filterable>
                <el-option v-for="item in samplingLocationOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检测指标">
              <el-select v-model="filterForm.waterQualityParameter" placeholder="请选择检测指标" clearable filterable>
                <el-option v-for="item in waterQualityParameterOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="mt-2">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-button type="primary" @click="handleAdd">
            <el-icon>
              <Plus />
            </el-icon> 新增记录
          </el-button>
          <el-button type="info" @click="handleImport">
            <el-icon>
              <Upload />
            </el-icon> 导入数据
          </el-button>
          <el-button type="success" :loading="exportLoading" @click="exportData">
            <el-icon>
              <Download />
            </el-icon> 导出数据
          </el-button>
        </el-col>
      </el-row>

      <el-table class="mt-2" :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="samplingTime" label="采样时间" width="160" />
        <el-table-column prop="samplingLocation" label="采样点位" width="120">
          <template #default="{ row }">
            {{ getDictLabel(samplingLocationOptions, row.samplingLocation) }}
          </template>
        </el-table-column>
        <el-table-column prop="waterQualityParameterName" label="检测指标" width="120">
          <template #default="{ row }">
            {{ getDictLabel(waterQualityParameterOptions, row.waterQualityParameterName) }}
          </template>
        </el-table-column>
        <el-table-column prop="parameterValue" label="检测值" width="100" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="operatorName" label="检测人员" width="120" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="150" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :total="pagination.total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑记录对话框 -->
    <el-dialog v-model="showDialog" :title="isEditMode ? '编辑水质化验记录' : '新增水质化验记录'" width="600px">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="采样时间" prop="samplingTime">
          <el-date-picker v-model="formData.samplingTime" type="datetime" placeholder="选择采样时间" style="width: 100%"
            value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="采样点位" prop="samplingLocation">
          <el-select v-model="formData.samplingLocation" placeholder="请选择采样点位" style="width: 100%">
            <el-option v-for="item in samplingLocationOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="检测指标" prop="waterQualityParameterName">
          <el-select v-model="formData.waterQualityParameterName" placeholder="请选择检测指标" style="width: 100%">
            <el-option v-for="item in waterQualityParameterOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="检测值" prop="parameterValue">
          <el-input v-model.number="formData.parameterValue" placeholder="请输入检测值" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="formData.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="检测人员" prop="operatorName">
          <el-input v-model="formData.operatorName" placeholder="请输入检测人员" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog v-model="importDialogVisible" title="导入化验数据" width="480px">
      <el-upload class="upload-block" drag accept=".xls,.xlsx" :auto-upload="false" :limit="1" :file-list="importFileList"
        @change="handleFileChange" @remove="handleFileRemove" @exceed="handleFileExceed">
        <el-icon class="el-icon--upload">
          <UploadFilled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="upload-tip-actions">
            <el-checkbox v-model="importUpdateSupport">是否更新已存在的数据</el-checkbox>
            <el-button type="primary" link @click="downloadTemplate">下载模板</el-button>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="importDialogVisible = false" :disabled="importUploading">取消</el-button>
        <el-button type="primary" :loading="importUploading" @click="submitImport">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Upload, UploadFilled } from '@element-plus/icons-vue'
import {
  getSamplingLocationList,
  getWaterQualityParameterList,
  getLabDataRecordList,
  getLabDataRecordDetail,
  addLabDataRecord,
  updateLabDataRecord,
  deleteLabDataRecord,
  exportLabDataRecord,
  importLabDataRecord,
  downloadLabDataTemplate
} from '@/api/prod_operate/water/manage/data_record'

// 筛选表单
const filterForm = reactive({
  dateRange: [],
  samplingLocation: '',
  waterQualityParameter: ''
})

// 采样点位选项
const samplingLocationOptions = ref([])

// 检测指标选项
const waterQualityParameterOptions = ref([])

// 表格数据
const tableData = ref([])

// 加载状态
const loading = ref(false)
const exportLoading = ref(false)

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const formData = reactive({
  samplingTime: '',
  samplingLocation: '',
  waterQualityParameterName: '',
  parameterValue: '',
  unit: '',
  operatorName: '',
  remark: ''
})

// 表单引用
const formRef = ref(null)

// 表单验证规则
const rules = {
  samplingTime: [
    { required: true, message: '请选择采样时间', trigger: 'change' }
  ],
  samplingLocation: [
    { required: true, message: '请选择采样点位', trigger: 'change' }
  ],
  waterQualityParameterName: [
    { required: true, message: '请选择检测指标', trigger: 'change' }
  ],
  parameterValue: [
    { required: true, message: '请输入检测值', trigger: 'blur' },
    { type: 'number', message: '检测值必须为数字', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  operatorName: [
    { required: true, message: '请输入检测人员', trigger: 'blur' }
  ]
}

// 对话框状态
const showDialog = ref(false)
const isEditMode = ref(false)
const currentRecordId = ref(null)

// 导入对话框
const importDialogVisible = ref(false)
const importFileList = ref([])
const importUpdateSupport = ref(false)
const importUploading = ref(false)

// 获取字典标签
const getDictLabel = (options, value) => {
  const item = options.find(item => item.dictValue === value)
  return item ? item.dictLabel : value
}

// 查询数据
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.dateRange = []
  filterForm.samplingLocation = ''
  filterForm.waterQualityParameter = ''
  handleSearch()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchData()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchData()
}

// 新增记录
const handleAdd = () => {
  isEditMode.value = false
  currentRecordId.value = null
  resetForm()
  showDialog.value = true
}

// 编辑记录
const handleEdit = async (row) => {
  try {
    loading.value = true
    const { data } = await getLabDataRecordDetail(row.id)
    if (data) {
      isEditMode.value = true
      currentRecordId.value = row.id
      Object.assign(formData, data)
      showDialog.value = true
    }
  } catch (error) {
    ElMessage.error('获取记录详情失败')
  } finally {
    loading.value = false
  }
}

// 删除记录
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除这条记录吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteLabDataRecord(row.id)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => { })
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    samplingTime: '',
    samplingLocation: '',
    waterQualityParameterName: '',
    parameterValue: '',
    unit: '',
    operatorName: '',
    remark: ''
  })
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    if (isEditMode.value) {
      // 编辑记录
      await updateLabDataRecord({
        ...formData,
        id: currentRecordId.value
      })
      ElMessage.success('编辑成功')
    } else {
      // 新增记录
      await addLabDataRecord(formData)
      ElMessage.success('新增成功')
    }

    showDialog.value = false
    fetchData()
  } catch (error) {
    if (error.response) {
      ElMessage.error(error.response.data.msg || '操作失败')
    }
  }
}

// 导出数据
const exportData = async () => {
  try {
    exportLoading.value = true
    const params = buildQueryParams(false)
    await exportLabDataRecord(params)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

// 导入
const handleImport = () => {
  importDialogVisible.value = true
  importFileList.value = []
  importUpdateSupport.value = false
}

const handleFileChange = (uploadFile, uploadFiles) => {
  importFileList.value = uploadFiles.slice(-1)
}

const handleFileRemove = () => {
  importFileList.value = []
}

const handleFileExceed = () => {
  ElMessage.warning('每次只能上传一个文件')
}

const submitImport = async () => {
  if (importFileList.value.length === 0) {
    ElMessage.warning('请先选择文件')
    return
  }
  try {
    importUploading.value = true
    const formData = new FormData()
    formData.append('file', importFileList.value[0].raw)
    formData.append('updateSupport', importUpdateSupport.value)
    const res = await importLabDataRecord(formData)
    const message = res.msg || res.data || '导入成功'
    ElMessageBox.alert(message, '导入结果', { dangerouslyUseHTMLString: true })
    importDialogVisible.value = false
    fetchData()
  } catch (error) {
    const msg = error?.response?.data?.msg || '导入失败'
    ElMessage.error(msg)
  } finally {
    importUploading.value = false
  }
}

const downloadTemplate = async () => {
  try {
    await downloadLabDataTemplate()
  } catch (error) {
    console.error('模板下载失败:', error)
    ElMessage.error('模板下载失败')
  }
}

const buildQueryParams = (withPagination = true) => {
  const params = {}
  if (withPagination) {
    params.pageNum = pagination.currentPage
    params.pageSize = pagination.pageSize
  }

  if (filterForm.dateRange && filterForm.dateRange.length === 2) {
    params.startTime = filterForm.dateRange[0]
    params.endTime = filterForm.dateRange[1]
  }

  if (filterForm.samplingLocation) {
    params.samplingLocation = filterForm.samplingLocation
  }

  if (filterForm.waterQualityParameter) {
    params.waterQualityParameter = filterForm.waterQualityParameter
  }

  return params
}

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    const params = buildQueryParams()
    const res = await getLabDataRecordList(params)
    tableData.value = res.rows || []
    pagination.total = res.total || 0
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 获取采样点位列表
const fetchSamplingLocationList = async () => {
  try {
    const { data } = await getSamplingLocationList()
    samplingLocationOptions.value = data || []
  } catch (error) {
    ElMessage.error('获取采样点位列表失败')
  }
}

// 获取检测指标列表
const fetchWaterQualityParameterList = async () => {
  try {
    const { data } = await getWaterQualityParameterList()
    waterQualityParameterOptions.value = data || []
  } catch (error) {
    ElMessage.error('获取检测指标列表失败')
  }
}

onMounted(() => {
  fetchSamplingLocationList()
  fetchWaterQualityParameterList()
  fetchData()
})
</script>

<style scoped>
.card-header :deep(.el-form-item) {
  margin-bottom: 0px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.upload-block {
  margin-bottom: 12px;
}

.upload-tip-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin-top: 8px;
}
</style>